﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ESAM_Assignment_3
{
    public partial class Site1 : System.Web.UI.MasterPage
    {
        #region Aesthetics features - The methods will check if authentication has been completed and proceed to update the display panel. | This segment of codes is NOT to be modified.
        /// <summary>
        /// Method to display the correct greeting based on system time
        /// </summary>
        /// <returns></returns>
        protected string Greeting()
        {
            int hour = DateTime.Now.Hour;
            if (hour < 12)
            {
                return "Good Morning ";
            }
            else if (hour >= 12 && hour < 17)
            {
                return "Good Afternoon ";
            }
            else
            {
                return "Good Evening ";
            }
        }

        /// <summary>
        /// Method to display a random chosen quote. This is the simple version. 
        /// </summary>
        /// <returns></returns>
        protected string GenerateQuote()
        {
            string[] Quotes = {"Walking on water and developing software from a specification are easy if both are frozen. (Unknown)", 
                              "If debugging is the process of removing software bugs, then programming must be the process of putting them in. (Edsger Dijkstra)",
                              "I have not failed. I've just found 10,000 ways that won't work. (Thomas A. Edison)",
                              "The best thing about a boolean is even if you are wrong, you are only off by a bit. (Unknown)",
                              "I don’t care if it works on your machine!  We are not shipping your machine! (Vidiu Platon)",
                              "I would love to change the world, but they won't give me the source code. (Unknown)",
                              "If people never did silly things, nothing intelligent would ever get done. (Ludwig Wittgenstein)",
                              "'Press any key to continue' Ehh.... where is the ANY key??? (Unknown)",
                              "I think it’s a new feature.  Don’t tell anyone it was an accident. (Larry Wall)",
                              "The only truly secure system is one that is powered off, cast in a block of concrete and sealed in a lead-lined room with armed guards. (Gene Spafford)",
                              "Passwords are like underwear: you don’t let people see it, you should change it very often, and you shouldn’t share it with strangers. (Chris Pirillo)"
                          };

            Random rand = new Random();
            return "<br><span align=RIGHT><font size=2 color=BLACK><i>" + Quotes[rand.Next(0, Quotes.Length)] + "</i></font></span>";
        }

        /// <summary>
        /// Method to update the display panel. 
        /// If the user has been authenticated, we will hide the LOGIN controls and display a friendly message greeting the authenticated user.
        /// </summary>
        /// <param name="IsUserAuthenticated"></param>
        /// <param name="Fullname"></param>
        private void UpdateDisplayPanel(bool IsUserAuthenticated, string Fullname)
        {
            if (IsUserAuthenticated)
            {
                //Hide the login controls
                lblUsername.Visible = false;
                tbxUsername.Visible = false;
                lblPassword.Visible = false;
                tbxPassword.Visible = false;
                btnLogin.Visible = false;

                //Display the login status
                lblLoginStatus.ForeColor = System.Drawing.Color.Blue;
                lblLoginStatus.Text = Greeting() + Fullname.ToUpper() + GenerateQuote();
                lblLoginStatus.Visible = true;
            }
            else
            {
                //Show the login controls
                lblUsername.Visible = true;
                tbxUsername.Visible = true;
                lblPassword.Visible = true;
                tbxPassword.Visible = true;
                btnLogin.Visible = true;
            }
        }

        #endregion

        #region Check the status of the database. If the database has not created yet, disallow the user from accessing any other webpages EXCEPT Default.aspx | This segment of codes is NOT to be modified.
        /// <summary>
        /// Method to check the status of the database. If the database has not been created yet, disallow the user from accessing any other webpage EXCEPT Default.aspx.
        /// Do NOT modify this method.
        /// </summary>
        private void CheckDatabaseExistence()
        {
            bool status = DBManager.IsDatabaseExist();
            btnLogin.Enabled = status;

            if (!status)
            {
                //Check to see which webpage the user is accessing
                string CurrentWebpage = System.IO.Path.GetFileName(Request.Url.ToString());
                string URL = "Default.aspx";

                if (CurrentWebpage.ToLower() != URL.ToLower())
                {
                    Session["ESAM_WARNING"] = CurrentWebpage;
                    Response.Redirect(URL);
                }
                else
                {
                    //Check if the user has tried accessing other webpages and a warning session has been set.
                    if (Session["ESAM_WARNING"] == null)
                    {
                        Session["ESAM_WARNING"] = "";
                    }

                    if (Session["ESAM_WARNING"].ToString().Length > 0)
                    {
                        Response.Write("<H3>You cannot access the webpage: " + Session["ESAM_WARNING"].ToString() + "!!! Remember to create the database and tables for this assignment. The button can be found on this webpage.</H3>");
                        Session["ESAM_WARNING"] = "";
                    }
                }
            }
        }

        #endregion

        #region Create the system menu.
        /// <summary>
        /// Method to add a menu separator. This segment of codes is NOT to be modified.
        /// </summary>
        private void AddMenuSeparator()
        {
            //Create the MenuItem for the separator.
            MenuItem mnuSeparator = new MenuItem();
            mnuSeparator.SeparatorImageUrl = "images/menu_separator_bar.gif";
            mnuSeparator.Selectable = false;
            mnuSeparator.Text = " ";
            mnuSeparator.Value = " ";
            Menu1.Items.Add(mnuSeparator);
        }

        /// <summary>
        /// Method to create the system menu. 
        /// If the parameter [IsUserAuthenticated] is TRUE, additional menu items will be created.
        /// If the parameter [IsUserAdmin] is TRUE, the adminstration menu item will be created.
        /// </summary>
        /// <param name="IsUserAuthenticated"></param>
        /// <param name="IsUserAdmin"></param>
        private void CreateSystemMenu(bool IsUserAuthenticated, bool IsUserAdmin)
        {
            //Ensure the menu is not populated
            Menu1.Items.Clear();

            MenuItem mnuHome = new MenuItem();
            if (IsUserAuthenticated)
            {
                mnuHome.NavigateUrl = "~/Default.aspx?Username=" + Request.QueryString["Username"];
            }
            else
            {
                mnuHome.NavigateUrl = "~/Default.aspx";
            }
            mnuHome.Text = "Home";
            mnuHome.Value = "Home";
            Menu1.Items.Add(mnuHome);
            AddMenuSeparator();

            MenuItem mnuComments = new MenuItem();
            mnuComments.Selectable = false;
            mnuComments.Text = "Comments";
            mnuComments.Value = "Comments";
            Menu1.Items.Add(mnuComments);

            MenuItem mnuListComments = new MenuItem();
            if (IsUserAuthenticated)
            {
                mnuListComments.NavigateUrl = "~/ListComments.aspx?Username=" + Request.QueryString["Username"];
            }
            else
            {
                mnuListComments.NavigateUrl = "~/ListComments.aspx";
            }
            mnuListComments.Text = "List All Comments";
            mnuListComments.Value = "ListAllComments";
            mnuComments.ChildItems.Add(mnuListComments);

            if (IsUserAuthenticated)
            {
                //Add the menu separator if the user has been authenticated.
                AddMenuSeparator();

                //Construct the menu for authenticated users
                MenuItem mnuAddComment = new MenuItem();
                mnuAddComment.NavigateUrl = "~/AddComment.aspx?Username=" + Request.QueryString["Username"];
                mnuAddComment.Text = "Add New Comment";
                mnuAddComment.Value = "AddNewComment";
                mnuComments.ChildItems.Add(mnuAddComment);

                if (IsUserAdmin)
                {
                    //Construct the menus for the ADMIN
                    MenuItem mnuAdmin = new MenuItem();
                    mnuAdmin.NavigateUrl = "~/Administration.aspx?Username=" + Request.QueryString["Username"];
                    mnuAdmin.Text = "Administration";
                    mnuAdmin.Value = "Administration";
                    Menu1.Items.Add(mnuAdmin);
                    AddMenuSeparator();

                    MenuItem mnuManageUser = new MenuItem();
                    mnuManageUser.NavigateUrl = "~/ManageUsers.aspx?Username=" + Request.QueryString["Username"];
                    mnuManageUser.Text = "Manage Users";
                    mnuManageUser.Value = "ManageUsers";
                    mnuAdmin.ChildItems.Add(mnuManageUser);

                    MenuItem mnuManageComments = new MenuItem();
                    mnuManageComments.NavigateUrl = "~/ManageComments.aspx?Username=" + Request.QueryString["Username"];
                    mnuManageComments.Text = "Manage Comments";
                    mnuManageComments.Value = "ManageComments";
                    mnuAdmin.ChildItems.Add(mnuManageComments);
                }

                MenuItem mnuChangePassword = new MenuItem();
                mnuChangePassword.NavigateUrl = "~/ChangePassword.aspx?Username=" + Request.QueryString["Username"]; ;
                mnuChangePassword.Text = "Change Password";
                mnuChangePassword.Value = "ChangePassword";
                Menu1.Items.Add(mnuChangePassword);
                AddMenuSeparator();

                MenuItem mnuLogout = new MenuItem();
                mnuLogout.NavigateUrl = "~/Logout.aspx";
                mnuLogout.Text = "Logout";
                mnuLogout.Value = "Logout";
                Menu1.Items.Add(mnuLogout);
            }
        }

        #endregion

        /// <summary>
        /// We are using the Page_Init() method to dynamically create the menu. 
        /// In order for the menu to be correctly displayed at each content page, the codes has to be placed in the Page_Init().
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            #region Determine if the require sessions are present. If not present, we will create the required sessions with the default values.
            if (Session[Common.ESAM_LOGIN] == null)
            {
                Session[Common.ESAM_LOGIN] = false;
            }

            if (Session[Common.ESAM_ADMIN] == null)
            {
                Session[Common.ESAM_ADMIN] = false;
            }

            if (Session[Common.ESAM_FULLNAME] == null)
            {
                Session[Common.ESAM_FULLNAME] = "";
            }

            #endregion

            //Check the status of the database
            CheckDatabaseExistence();

            bool IsUserAuthenticated = (bool)Session[Common.ESAM_LOGIN];
            bool IsUserAdmin = (bool)Session[Common.ESAM_ADMIN];
            string Fullname = (string)Session[Common.ESAM_FULLNAME];

            CreateSystemMenu(IsUserAuthenticated, IsUserAdmin);
            UpdateDisplayPanel(IsUserAuthenticated, Fullname);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //We need to call Page_Init() to ensure the menu is created correctly after the PostBack
            Page_Init(sender, e);
        }

        /// <summary>
        /// Button event to handle the LOGIN.
        /// You will have to modify the codes as part of the assignment's requirements. 
        /// However, you MUST maintain the following session variables:
        ///    Session[Common.ESAM_ADMIN] - to indicate if the user is an ADMIN
        ///    Session[Common.ESAM_LOGIN] - to indicate if the user has successfully been authenticated
        ///    Session[Common.ESAM_FULLNAME] - to indicate the user's fullname
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = tbxUsername.Text.ToLower();
            string password = tbxPassword.Text;

            bool success = false;
            bool IsAdmin = false;
            string fullname = "";
            string URL = "";

            if (username == "admin" && password == "admin")
            {
                //Initialise the values for the admin user
                success = true;
                IsAdmin = true; //Indicate the user is an ADMIN
                fullname = "Admin";
                URL = "Administration.aspx?Username=" + username;
            }
            else
            {
                //Check if the user's supplied credentials matches those stored in database
                success = UserClass.UnsecuredLogin(username, password);
                if (success)
                {
                    //Initialise the values for the normal user
                    fullname = UserClass.GetFullname(username);
                    URL = "ListComments.aspx?Username=" + username;
                }
            }

            if (!success)
            {
                //User cannot be authenticated, let's display an error message.
                lblLoginStatus.Text = "<br>Login is unsuccessful. Please try again.";
                lblLoginStatus.ForeColor = System.Drawing.Color.Red;
                lblLoginStatus.Visible = true;

                //Initialise the session variables back to the default values.
                Session[Common.ESAM_ADMIN] = false;
                Session[Common.ESAM_LOGIN] = false;
                Session[Common.ESAM_FULLNAME] = null;
            }
            else
            {
                //Store user's details
                CookieClass myCookie = new CookieClass();
                myCookie.WriteCookie(Context, username, password);

                //Setup the session
                success = true;
                Session[Common.ESAM_ADMIN] = IsAdmin; //Indicate the user is an ADMIN
                Session[Common.ESAM_LOGIN] = true; //Indicate the user has successfully logon
                Session[Common.ESAM_FULLNAME] = fullname;
                Response.Redirect(URL);
            }
        }
    }
}